package com.ton.utils.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class RestTemplateUtils {

    public static String doGet(String url, Map<String, String> header, Map<String, Object> params) {
        return getParams(url, header, params);
    }

    public static String doPost(String url, Map<String, String> header, Map<String, Object> params) {
        return postParams(url, header, params);
    }


    public static String getParams(String url, Map<String, String> header, Map<String, Object> params) {
        RestTemplate restTemplate = null;
        try {
            restTemplate = getRestTemplate();
        } catch (Exception e) {
            log.error("获取RestTemplate失败！！！");
            e.printStackTrace();
            return "";
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        for (String key : header.keySet()) {
            headers.add(key, header.get(key));
        }
        String joinUrl = joinParam(url, params);

        // 构建HttpEntity对象，包含请求头和可能的请求体（GET请求通常无请求体，此处为空）
        org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity<String>(null, headers);

        // 发送GET请求并获取响应
        // 替换为实际期望的响应类型，如：YourResponseClass.class
        ResponseEntity<String> response = null;

        try {
            response = restTemplate.exchange(joinUrl, HttpMethod.GET, requestEntity, String.class);
        } catch (Exception e) {
            log.error("RestTemplate发送GET请求出错！", e);
            //e.printStackTrace();
            return "";
        }
        if (Objects.nonNull(response)) {
            return response.getBody();
        }
        return "";
    }

    public static String postParams(String url, Map<String, String> header, Map<String, Object> params) {
        RestTemplate restTemplate = null;
        try {
            restTemplate = getRestTemplate();
        } catch (Exception e) {
            log.error("获取RestTemplate失败！！！");
            e.printStackTrace();
            return "";
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        for (String key : header.keySet()) {
            headers.add(key, header.get(key));
        }

        //body
//        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        // 构建HttpEntity对象，包含请求头和可能的请求体（GET请求通常无请求体，此处为空）
        org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity<>(params, headers);


        // 发送GET请求并获取响应
        // 替换为实际期望的响应类型，如：YourResponseClass.class
        ResponseEntity<String> response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        } catch (Exception e) {
            log.error("RestTemplate发送POST请求出错！", e);
            e.printStackTrace();
            return "";
        }

        if (Objects.nonNull(response)) {
            // 处理响应结果
            return response.getBody();
        }
        return "";
    }

    //取消SSL校验
    public static void disableSslVerification(HttpComponentsClientHttpRequestFactory requestFactory) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        ;

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLSocketFactory(csf).build();
        requestFactory.setHttpClient(httpClient);

    }

    public static RestTemplate getRestTemplate() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        SimpleClientHttpRequestFactory setting = new SimpleClientHttpRequestFactory();
        ;

        // 配置代理
        String proxyHost = "127.0.0.1";
        int proxyPort = 65221; //配置代理端口

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        setting.setProxy(proxy);

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(setting);
        //    disableSslVerification(requestFactory); //关闭证书校验
        //     restTemplate.setRequestFactory(requestFactory);
        //        requestFactory.setReadTimeout(2000);
        //    requestFactory.setConnectTimeout(2000);
        return restTemplate;
    }

    private static String joinParam(String url, Map<String, Object> params) {
        if (params == null || params.size() == 0) {
            return url;
        }

        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?");

        int counter = 0;
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key == null) {
                continue;
            }

            if (counter == 0) {
                urlBuilder.append(key).append("=").append(value);
            } else {
                urlBuilder.append("&").append(key).append("=").append(value);
            }
            counter++;
        }

        return urlBuilder.toString();
    }
}
